package com.yanfan.zutai.controller;

import com.alibaba.fastjson2.JSON;
import com.yanfan.common.annotation.Log;
import com.yanfan.common.core.controller.BaseController;
import com.yanfan.common.core.domain.AjaxResult;
import com.yanfan.common.core.domain.model.LoginUser;
import com.yanfan.common.core.page.TableDataInfo;
import com.yanfan.common.enums.BusinessType;
import com.yanfan.common.utils.SecurityUtils;
import com.yanfan.common.utils.poi.ExcelUtil;
import com.yanfan.getui.config.GTPushConfig;
import com.yanfan.mqtt.manager.MqttRemoteManager;
import com.yanfan.mqtt.model.PushMessageBo;
import com.yanfan.zutai.aop.SysInitData;
import com.yanfan.zutai.aop.SysInitUpdateData;
import com.yanfan.zutai.aop.SysQueryData;
import com.yanfan.zutai.domain.BAppDept;
import com.yanfan.zutai.domain.BDeviceWarn;
import com.yanfan.zutai.service.IBAppDeptService;
import com.yanfan.zutai.util.Detect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 个推Controller
 *
 * @author ruoyi
 * @date 2023-04-22
 */
@RestController
@RequestMapping("/zutai/bAppDept")
public class BAppDeptController extends BaseController {
    @Autowired
    private IBAppDeptService bAppDeptService;
    @Resource
    private MqttRemoteManager remoteManager;

    /**
     * 查询个推列表
     */
    //@PreAuthorize("@ss.hasPermi('ghxx:bAppDept:list')")
    @GetMapping("/list")
    @SysQueryData
    public TableDataInfo list(BAppDept bAppDept) {
        startPage();
        List<BAppDept> list = bAppDeptService.selectBAppDeptList(bAppDept);
        return getDataTable(list);
    }

    /**
     * 导出个推列表
     */
    //@PreAuthorize("@ss.hasPermi('ghxx:bAppDept:export')")
    @Log(title = "个推", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BAppDept bAppDept) {
        List<BAppDept> list = bAppDeptService.selectBAppDeptList(bAppDept);
        ExcelUtil<BAppDept> util = new ExcelUtil<BAppDept>(BAppDept.class);
        util.exportExcel(response, list, "个推数据");
    }

    /**
     * 获取个推详细信息
     */
    //@PreAuthorize("@ss.hasPermi('ghxx:bAppDept:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(bAppDeptService.selectBAppDeptById(id));
    }

    /**
     * 新增个推
     */
    //@PreAuthorize("@ss.hasPermi('ghxx:bAppDept:add')")
    @Log(title = "个推", businessType = BusinessType.INSERT)
    @PostMapping
    @SysInitData
    public AjaxResult add(@RequestBody BAppDept bAppDept) {
        return toAjax(bAppDeptService.insertBAppDept(bAppDept));
    }

    /**
     * 修改个推
     */
    //@PreAuthorize("@ss.hasPermi('ghxx:bAppDept:edit')")
    @Log(title = "个推", businessType = BusinessType.UPDATE)
    @PutMapping
    @SysInitUpdateData
    public AjaxResult edit(@RequestBody BAppDept bAppDept) {
        if (Detect.notEmpty(bAppDept.getMessage())) {
            Integer code = GTPushConfig
                    .getInstance()
                    .sendMessage(bAppDept.getClientId(), bAppDept.getTitle(), bAppDept.getMessage());
            String topic = "/IOT/WULIANYUN/SENDWARNMESSAGE";
            BDeviceWarn bDeviceWarn = new BDeviceWarn();
            bDeviceWarn.setUpdateBy(bAppDept.getUserName());
            bDeviceWarn.setWarnTime(new Date());
            bDeviceWarn.setWarnMessage(bAppDept.getMessage());
            bDeviceWarn.setWarnType(bAppDept.getMessage());
            bDeviceWarn.setDeviceName("个推通知设备");
            bDeviceWarn.setAddress("本机天安门");
            bDeviceWarn.setDeviceMac("123456789");
            bDeviceWarn.setDeptIdStrs("0,100,");
            // 发送至前端
            PushMessageBo messageBo = new PushMessageBo();
            messageBo.setTopic(topic);
            messageBo.setMessage(JSON.toJSONString(bDeviceWarn));
            remoteManager.pushCommon(messageBo);
            if (code == 200) {
                return AjaxResult.success("发送成功");
            } else {
                return AjaxResult.error("发送失败");
            }
        } else {
            return toAjax(bAppDeptService.updateBAppDept(bAppDept));
        }
    }

    /**
     * 删除个推
     */
    //@PreAuthorize("@ss.hasPermi('ghxx:bAppDept:remove')")
    @Log(title = "个推", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(bAppDeptService.deleteBAppDeptByIds(ids));
    }

    /**
     * 个推
     */
    @Log(title = "个推", businessType = BusinessType.INSERT)
    @PostMapping("/insertAppDept")
    public AjaxResult insertAppDept(@RequestBody BAppDept bAppDept) {
        BAppDept bAppDeptQuery = new BAppDept();
        bAppDeptQuery.setClientId(bAppDept.getClientId());
        List<BAppDept> bAppDepts = bAppDeptService.selectBAppDeptList(bAppDeptQuery);
        if (bAppDepts.size() == 0) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            bAppDept.setUserName(loginUser.getUsername());
            bAppDept.setDeptId(loginUser.getUser().getDeptId());
            bAppDept.setDeptName(loginUser.getUser().getDept().getDeptName());
            bAppDept.setNickName(loginUser.getUser().getNickName());
            bAppDeptService.insertBAppDept(bAppDept);
        } else {
            bAppDept = bAppDepts.get(0);
            LoginUser loginUser = SecurityUtils.getLoginUser();
            bAppDept.setUserName(loginUser.getUsername());
            bAppDept.setDeptId(loginUser.getUser().getDeptId());
            bAppDept.setDeptName(loginUser.getUser().getDept().getDeptName());
            bAppDept.setNickName(loginUser.getUser().getNickName());
            bAppDeptService.updateBAppDept(bAppDept);
        }
        return AjaxResult.success();
    }
}
